package com.bingarchive;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

abstract class AbstractContact {
//	private static final String	XML_HEAD = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
	static final long DAY_MILLISECOND = 86400000;
	
	static String ReadXML(String stUrl) {
		String _stXML = HttpContact(stUrl);

		if (_stXML.length() <= 0) {
			_stXML = UrlContact(stUrl);
			if (_stXML.length() <= 0) {
				_stXML = "";
			}
		}
		
		return _stXML;
	}
	
	static byte[] ReadFile(URL url) throws Exception {
		HttpURLConnection _huConn = (HttpURLConnection) url.openConnection();
		if (_huConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
			return null;
		}

		InputStream _inStream = _huConn.getInputStream();

		ByteArrayOutputStream _baoutStream = new ByteArrayOutputStream();

		byte[] _btBuffer = new byte[1024];
		int _ntLen = 0;
		while ((_ntLen = _inStream.read(_btBuffer)) != -1) {
			_baoutStream.write(_btBuffer, 0, _ntLen);
		}
		_baoutStream.flush();

		byte[] _btData = _baoutStream.toByteArray();

		return _btData;
	}
	
	private static String HttpContact(String stUrl) {
		String _stXML = new String();

		DefaultHttpClient _dhc = new DefaultHttpClient();
		try {
			HttpGet _httpget = new HttpGet(stUrl);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			_stXML = _dhc.execute(_httpget, responseHandler);
		} catch (Exception e) {
			e.printStackTrace();
		}
		_dhc.getConnectionManager().shutdown();

		return _stXML;
	}

	private static String UrlContact(String stUrl) {
		String _stXML = new String();

		try {
			URL _url = new URL(stUrl);
			HttpURLConnection _huConn = (HttpURLConnection) _url
					.openConnection();
			if (_huConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return _stXML;
			}

			InputStreamReader _insReader = new InputStreamReader(
					_huConn.getInputStream(), "utf-8");
			int i;
			while ((i = _insReader.read()) != -1) {
				_stXML = _stXML + (char) i;
			}
			_insReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return _stXML;
	}
}
